<?php
class system_image_watermark {

	protected $oldImage = null;
	protected $fileName = null;
	protected $dimensions = array('width' => 0, 'height' => 0);
	protected $options = array();
	
	public function __construct($filename, $options = array()) {
		$this->fileName = $filename;
		$format = $this->determineFormat();
		$this->setOptions($options);
		switch($format) {
			case 'GIF':
				$this->oldImage = imagecreatefromgif($this->fileName);
				break;
			case 'JPG':
				$this->oldImage = imagecreatefromjpeg($this->fileName);
				break;
			case 'PNG':
				$this->oldImage = imagecreatefrompng($this->fileName);
				break;
			case 'STRING':
				$this->oldImage = imagecreatefromstring($this->fileName);
				break;
		}
		$this->dimensions = array('width' => imagesx($this->oldImage), 'height' => imagesy($this->oldImage));
	}
	
	public function __destruct() {
		if(is_resource($this->oldImage)) {
			imagedestroy($this->oldImage);
		}
	}
	
	public function getImage() {
		return $this->oldImage;
	}
	
	public function getDimensions() {
		return $this->dimensions;
	}
	
	public function getWidth() {
		return $this->dimensions['width'];
	}
	
	public function getHeight() {
		return $this->dimensions['height'];
	}

	protected function determineFormat() {
		$formatInfo = getimagesize($this->fileName);
		if($formatInfo === false) {
			throw new system_exception('Watermark image is not a valid image: ' . $this->fileName);
			return null;
		}
		$format = null;
		$mimeType = isset($formatInfo['mime']) ? $formatInfo['mime'] : null;	
		switch($mimeType) {
			case 'image/gif':
				$format = 'GIF';
				break;
			case 'image/jpeg':
				$format = 'JPG';
				break;
			case 'image/png':
				$format = 'PNG';
				break;
			default:
				throw new system_exception('Image format not supported: ' . $mimeType);
		}
		return $format;
	}
	/**
	 * @return system_image_watermark
	 */
	public function setOptions($options = array()) {
		if(!is_array($this->options)) {
			$this->options = array();
		}
		if(sizeof($this->options) == 0) {
			$defaultOptions = array(
				'margin' => 5,
				'position' => 9, // 1 2 3
								 // 4 5 6
								 // 7 8 9
								 // rand 0
				'minWidth' => 500, // 打水印最小宽度
				'minHeight' => 500 // 打水印最小高度
			);
		} else {
			$defaultOptions = $this->options;
		}		
		$this->options = array_merge($defaultOptions, $options);
		return $this;
	}
	public function getOptions() {
		return $this->options;
	}
}
